<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class goodController extends Controller
{
	public function __construct()
  {
    $this->middleware('login');
  }
	public function add()
	{
		$data = DB::table('types as t1')
        ->select('t1.*','t2.tname as pname',DB::raw("concat(t1.path,',',t1.tid) as sortpath"))
        ->leftJoin('types as t2','t1.pid','=','t2.tid')
        ->orderBy('sortpath')
        ->get();
        foreach ($data as $k => $v)
        {
           $num = substr_count($v->path, ',');
           $str = str_repeat('&nbsp;', $num*6).'||---';
           $data[$k]-> tname = $str.$v->tname; 
        }

		return view('admin.good.add', ['title' => '商品添加','data'=>$data]);
	}

	public function insert(Request $request)
	{
		$this->validate($request, [
        'gname' => 'required',
        'price' => 'required',
        'gdesc' => 'required',
        'gpic' => 'image',
        'tid' => 'required'
        ],[
        'gname.required' => '商品名称不能为空',
        'price.required' => '商品价格不能为空',
        'gdesc.required' => '商品描述不能为空',
        'gpic.image' => '必须传一张商品图片',
        'tid.required' => '分类不能我空'
        ]);
   
		$data = $request -> except('_token');
		//dd($data);
		$data['tname'] = DB::table('types')->where('tid',$data['tid'])->first()->tname;
        //dd($data);
		if($request -> hasFile('gpic'))
		{

			if($request -> file('gpic') -> isValid())
			{
				$extension = $request -> file('gpic') -> getClientOriginalExtension();

				$filename = mt_rand(1000000,9999999).'.'.$extension;
				$dir = './uploads/avatar/';

				$request -> file('gpic') -> move($dir, $filename);
				$data['gpic'] = '/uploads/avatar/'.$filename;
			}
		}else
		{
			$data['gpic'] = '/uploads/avatar/default.jpg';
		}
	    $data['ctime'] = Date('Y-m-d H:i:s');	
		$goodRes = DB::table('goods') -> insert($data);
		if($goodRes)
		{
			return redirect('/admin/good/find') -> with(['info' => '添加成功']);
		}else
		{
			return back() -> with(['info' => '添加失败']);
		}
	}

	public function find(Request $request)
	{
		$num = $request -> input('num',2);
		$keywords = $request -> input('keywords','');
        
		$data = DB::table('goods')
				-> where('gname', 'like', '%'.$keywords.'%')
				-> paginate($num);
   //      $tid = DB::table('goods')->select('tid')->get();
   //       foreach ($tid as $k => $v) {
   //       	 $tid[$k]=$v;
   //       	 dd($tid);
   //       }

		 // $tname = DB::table('types')->where('tid',$tid)->first();
			
		return view('admin.good.find',['data' => $data, 'request' => $request -> all(), 'title' => '商品信息']);
	}

	//ajax 修改商品库存
	public function changeCnt(Request $request)
	{
		$id = $request -> gid;
		$cnt = $request -> cnt;

		$res = DB::table('goods') -> where('gid', $id) -> update(['cnt' => $cnt]);

		if($res)
		{
			return 1;
		}else
		{
			return 0;
		}
	}

	public function edit($gid)
	{
		$data = DB::table('goods') -> where('gid', $gid) -> first();

		return view('admin.good.edit', ['title' => '商品修改', 'data' => $data]);
	}

	public function update(Request $request)
	{
		$this->validate($request, [
        'gname' => 'required',
        'price' => 'required',
        'gdesc' => 'required',
        'gpic' => 'image',
        ],[
        'gname.required' => '商品名称不能为空',
        'price.required' => '商品价格不能为空',
        'gdesc.required' => '商品描述不能为空',
        'gpic.image' => '必须传一张商品图片',
        ]);

		$gid = $request -> gid;

		$data = $request -> except('_token');

		if($request -> hasFile('gpic'))
		{

			if($request -> file('gpic') -> isValid())
			{
				$extension = $request -> file('gpic') -> getClientOriginalExtension();

				$filename = mt_rand(1000000,9999999).'.'.$extension;
				$dir = './uploads/avatar/';

				$request -> file('gpic') -> move($dir, $filename);
				$data['gpic'] = '/uploads/avatar/'.$filename;

				$oldGpic = DB::table('goods') -> where('gid',$gid) -> first() -> gpic;
				if(!empty($oldGpic))
				{
					if($oldGpic != '/uploads/avatar/default.jpg')
					{
						if(file_exists('.'.$oldGpic))
						{
							unlink('.'.$oldGpic);
						}
					}
				}
			}
		}else
		{
			$data['gpic'] = '/uploads/avatar/default.jpg';
		}

		$res = DB::table('goods') -> where('gid',$gid) -> update($data);

		if($res)
		{
			return redirect('/admin/good/find') -> with(['info' => '修改成功']);
		}else
		{
			return back() -> with(['info' => '修改失败']);
		}
	}

	public function delete($gid)
	{
		$gpic = DB::table('goods') -> where('gid',$gid) -> first() -> gpic;
		$res = DB::table('goods') -> where('gid',$gid) -> delete();
		if($res)
		{
			if(!empty($gpic))
				{
					if($gpic != '/uploads/avatar/default.jpg')
					{
						if(file_exists('.'.$gpic))
						{
							unlink('.'.$gpic);
						}
					}
				}
		    return redirect('/admin/good/find') -> with(['info' => '删除成功']);
		}else
		{
			return back() -> with(['info' => '删除失败']);
		}
		
	}
    
}
